/*
CpGears v1.0

Copyright (c) 2010 Yves Riel http://www.flash-factor.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package cpgears.properties 
{
	import cpgears.helpers.CaptivateHelper;
	import cpgears.helpers.StringUtil;
	import cpgears.log.*;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedSuperclassName;
	
	/**
	 * Base implementation of a widget properties object.
	 * 
	 * @author Whyves
	 */
	public dynamic class WidgetPropertiesBase implements IWidgetProperties
	{
		private static var mLogger:ILogger = null;
		
		private var mParametersObject:Object = null;
		
		private var mPrototype:* = null;
		
		
		/**
		 * Creates an object containing the widget properties.
		 */
		public function WidgetPropertiesBase(qualifiedClassName:String)
		{
			mLogger = LogManager.getLogger(this);
			mPrototype = { }; // (classPrototype == null) ? prototype : classPrototype;
			objectType = (qualifiedClassName == null) ? getQualifiedSuperclassName(this) : qualifiedClassName;
			setDefaultValues();
		}

		/**
		 * Sets the widget property default values.
		 * 
		 * <P>Override this function to initialize the widget default values. This
		 * function is called automatically when the object is created.</P>
		 */
		protected function setDefaultValues():void {
		}
		
		/**
		 * @inheritDoc
		 */
		public function initializeFromString(xmlString:String):void {
			var xmlObject:Object = null;
			try {
				xmlObject = CaptivateHelper.createObjectFromXmlData(new XML(xmlString));
			}
			catch (err:Error){
				// Error in XML format just return
				mLogger.error("Error processing XML string into an object");
				return;
			}
			initializeFromObject(xmlObject);
		}
		
		/**
		 * @inheritDoc
		 */
		public function initializeFromObject(object:Object):void {
			if (mParametersObject != null) clearProperty();
			mParametersObject = object;
			var propertiesObject:IWidgetProperties  = null;
			for (var property:String in mParametersObject) {
				try {
					if (this[property] is IWidgetProperties) {
						this[property] = getWidgetPropertiesInstance(mParametersObject[property]);
					} else if (this[property] is Array) {
						var newArray:Array = [];
						for each (var item:Object in mParametersObject[property]) {
							if (item.hasOwnProperty("objectType")) {
								newArray.push(getWidgetPropertiesInstance(item));
							} else {
								newArray.push(item);
							}
						}
						this[property] = newArray;
					} else {
						this[property] = mParametersObject[property];
					}
				}
				catch (err:Error){
					mLogger.error("Error assigning widget parameter '{0}': {1}", property,err.message);
				}
			}
		}
		
		/**
		 * @private
		 * 
		 * Creates and initializes the widget properties instance.
		 */
		private function getWidgetPropertiesInstance(objectParameters:Object):IWidgetProperties {
			var instance:IWidgetProperties = instantiateWidgetProperties(objectParameters["objectType"]);
			instance.initializeFromObject(objectParameters);
			return instance;
		}
		
		/**
		 * @private
		 * 
		 * Creates the Widget Properties instance.
		 */
		private function instantiateWidgetProperties(className:String):IWidgetProperties {
			try {
				var instanceClass:Class = getDefinitionByName(className) as Class;
				return new instanceClass() as IWidgetProperties;
			} catch (err:Error){
				mLogger.error("Could not instantiate '{0}'.", className);
			}
			return new NullPropertiesObject();
		}
		
		/**
		 * Returns a property value.
		 * 
		 * @param	name The name of the property.
		 * 
		 * @return The property value.
		 */
		protected function getProperty(name:String):* {
			try {
				return mPrototype[name];
			} catch (err:Error) {
				mLogger.warn("Could not retrieve property '{0}' from prototype object.", name);
			}
			return null;
		}
		
		/**
		 * Sets a widget property.
		 * 
		 * <P>By using this method to set a widget property, the property will be available
		 * to the Captivate IDE for storage purposes.</P>
		 * 
		 * @param	name The name of the property.
		 * @param	value The value of the property.
		 */
		protected function setProperty(name:String, value:*):void {
			if (StringUtil.isNullOrEmpty(name)) {
				mLogger.warn("Property name was either null or empty. Cannot set it in the prototype object.");
			}
			if (!isReservedKeyword(name)) mPrototype[name] = value;
		}
		
		/**
		 * String representing the object type to rebuild.
		 */
		public function get objectType():String {
			return mPrototype["objectType"] as String;
		}
		public function set objectType(value:String):void {
			if (value == null) value = "";
			mPrototype["objectType"] = value;
		}

		/**
		 * Clears the object from the previous properties
		 */
		private function clearProperty():void {
			for (var property:String in mParametersObject) {
				delete this[property];
			}
		}
		
		/**
		 * @inheritDoc
		 */
		public function getPropertiesObject():Object {
			var propertiesObject:Object = { };
			copyProperties(this, propertiesObject);
			copyProperties(mPrototype, propertiesObject);
			return propertiesObject;
		}
		
		/**
		 * @private
		 * 
		 * Copies object dynamic properties into another object.
		 */
		private function copyProperties(source:Object, target:Object):void {
			for (var property:String in source) {
				if (source[property] is IWidgetProperties) {
					target[property] = IWidgetProperties(source[property]).getPropertiesObject();
				} else if (source[property] is Array) {
					var newArray:Array =  [];
					for (var i:int = 0; i < source[property].length; i++) {
						if (source[property][i] is IWidgetProperties) {
							newArray.push(source[property][i].getPropertiesObject())
						} else {
							newArray.push(source[property][i]);
						}
						target[property] = newArray;
					}
				} else {
					target[property] = source[property];
				}
			}
		}
		
		/**
		 * @private
		 */
		private function isReservedKeyword(name:String):Boolean {
			var reserved:Boolean = (name == "objectType");
			if (reserved) mLogger.error("'{0}' is a reserved keyword in CpGears.", name);
			return reserved;
		}
	}
}